<script lang="ts" setup>
import { onMounted, ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { saveAs } from 'file-saver';
import { backgExoandNode } from '@/common/utils/backg-expand-node'
import { getLeaderListApi } from '@/common/apis/organization';
import { getLeadertreeData } from '@/common/utils/backg-tree';
import { getSysUserApi, deleteSysUserIdApi, getSysUserIdApi, getSysUserExcelApi } from '@/common/apis/information'
import type { UnwrapRef } from 'vue';
import type { DataItem } from '@/common/types/information-type'
import type { SwitchPagination } from '@/common/types/information-type'
import backgNotice from '@/common/components/backg-information/backg-notice.vue'
import backgFileUpload from '@/common/components/backg-information/backg-file-upload.vue';
import backgAllocationRole from '@/common/components/backg-information/backg-allocation-role.vue';


// 初始化路由
const router = useRouter();

// 搜索
const userName = ref<string>('');
// 储存的数据 部门成员
const memberData = ref<DataItem[]>([])
// 储存选中的数据
const selectedRowData = ref()
// 储存员工基本信息
const staffinformation = ref()
// 设置树节点
const leaderListData = ref<string[]>();
// 默认展开根节点
const defaultExpandedKeys = ref<string[]>([]);
// 间距
const size = ref(8)
// 弹框
const ModalShow1 = ref()
const ModalShow2 = ref()
const ModalShow3 = ref()

const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

// 展开状态
const expandedKeys = ref<string[]>([]);
// 选中状态
const selectedKeys = ref<string[]>([]);

// 如果为空 则展示这个图片
const items = ref({
  image: "src/assets/common/bigUserHeader.png"
})

// page分页
const pagination = reactive({
  departmentId: null as number | null,
  page: 1,  // 当前页码
  pagesize: 10, // 每页条数
  keyword: '', // 搜索关键字
  total: 0, // 总数据条数
});


// 标题
const columns = [
  {
    title: '头像',
    dataIndex: 'staffPhoto',
    id: 'staffPhoto'
  },
  {
    title: '姓名',
    dataIndex: 'username',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
  },
  {
    title: '工号',
    dataIndex: 'workNumber',
  },
  {
    title: '聘用形式',
    dataIndex: 'formOfEmployment',
  },
  {
    title: '部门',
    dataIndex: 'departmentName',
  },
  {
    title: '入职时间',
    dataIndex: 'timeOfEntry',
  },
  {
    title: '操作',
    dataIndex: 'operate',
  },
];


// 获取部门列表
const getLeaderListData = async () => {
  const res = await getLeaderListApi();
  const data = res.data.data;
  leaderListData.value = getLeadertreeData(data);


  console.log(leaderListData.value, 'leaderListData')

  // 设置默认展开所有节点
  if (leaderListData.value.length > 0) {
    const allKeys = backgExoandNode(leaderListData.value);
    defaultExpandedKeys.value = allKeys; // 默认展开所有节点
    expandedKeys.value = allKeys; // 设置展开状态
  }
};

// 获取-员工列表
const getSysUserData = async () => {
  const res = await getSysUserApi(pagination)
  memberData.value = res.data.data.rows
  // 获取总数据条数
  pagination.total = res.data.data.total
}

// 点击分页获取数据
const handleTableChange = (page: SwitchPagination) => {
  console.log(page, 'page')
  pagination.page = page.current; // 更新当前页码
  pagination.pagesize = page.pageSize; // 更新每页条数
  getSysUserData(); // 加载新数据
};

// 模糊搜索
const filterrdData = computed(() => {
  // 判断有没有输入信息 无则返回所有数据
  if (!userName.value) {
    return memberData.value
  }
  return memberData.value.filter((item: DataItem) => Object.values(item).some((value) =>
    String(value).toLowerCase().includes(userName.value.toLocaleUpperCase())
  ))
})

// 点击树节点，更新 departmentId 并获取员工数据
const handleTreeSelect = (selectedKeys: number[]) => {
  console.log(selectedKeys, 'selectedKeys')
  pagination.departmentId = selectedKeys.length ? selectedKeys[0] : null;
  getSysUserData(); // 重新获取员工数据
};

// 点击-群发通知
const clickNotification = () => {
  if (selectedRowData.value && selectedRowData.value.length > 0) {
    ModalShow1.value.showModal()
  } else {
    message.warning('请先选择要群发的员工!');
  }
}

// 点击-员工导入
const onClickFileUpload = () => {
  ModalShow3.value.showModal()
}

// 点击员工导出
const onClickFileExport = async () => {
  const result = await getSysUserExcelApi()
  // 创建 Blob 对象
  const blob = new Blob([result.data], { type: result.data.type });
  // 使用 file-saver 保存文件
  saveAs(blob, '员工信息表.xlsx');
};

const rowSelection = ref({
  checkStrictly: false,
  // 点击多选框的数据
  onChange: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    // 保存数据
    selectedRowData.value = selected
    console.log(record, selected, selectedRows, 'onChange');
  },
  onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    console.log(record, selected, selectedRows, 'onSelect');
    selectedRowData.value = selectedRows
  }
});


// role 角色
const role = async (id: string) => {
  ModalShow2.value.showModal()
  const res = await getSysUserIdApi({ id, ...memberData.value })
  staffinformation.value = res.data.data
};

// deleteItem 删除
const deleteItem = async (id: string) => {
  const res = await deleteSysUserIdApi(id)
  if (res.data.code === 10000) {
    // 刷新人工列表
    getSysUserData()
    message.success('删除成功！')
  } else {
    message.error(res.data.message)
  }
}


onMounted(() => {
  getLeaderListData();
  getSysUserData()
});

</script>

<template>
  <div class="information">
    <!-- 侧边栏 -->
    <div>
      <div class="components-input-demo-presuffix">
        <a-input v-model:value="userName" placeholder="输入员工姓名全员搜索">
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>
      </div>
      <a-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" :tree-data="leaderListData"
        :default-expanded-keys="defaultExpandedKeys" @select="handleTreeSelect">
        <template #title="{ title, key }">
          <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
          <template v-else>{{ title }}</template>
        </template>
      </a-tree>
    </div>

    <!-- 部门成员展示 -->
    <div style="width: 80%;">
      <a-space class="information-member" align="center">
        <a-button @click="clickNotification">群发通知</a-button>
        <a-space :size="size">
          <a-button type="primary" @click="router.push('/add-employee')">添加员工</a-button>
          <a-button @click="onClickFileUpload">excel导入</a-button>
          <a-button @click="onClickFileExport">excel导出</a-button>
        </a-space>
      </a-space>

      <!-- 员工数据列表 -->
      <a-table :columns="columns" :data-source="filterrdData" :row-selection="rowSelection" rowKey="id"
        :pagination="pagination" @change="handleTableChange">
        <template #bodyCell="{ column, record }">

          <template v-if="column.dataIndex === 'formOfEmployment'">
            <span v-if="record.formOfEmployment === 1">正式员工</span>
            <span v-else>未聘用</span>
          </template>
          <template v-if="column.dataIndex === 'staffPhoto'">
            <a-image :preview="false" style="width: 50px;" :src="record.staffPhoto ? record.staffPhoto : items.image"
              alt="员工头像" />
          </template>

          <template v-if="column.dataIndex === 'operate'">
            <div class="editable-row-operations">
              <!-- 取消-保存 -->
              <span v-if="editableData[record.id]">
                <!-- 取消二次确认 -->
                <a-popconfirm title="你确定取消么?">
                  <a>取消</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <a @click="router.push(`/add-employee/${record.id}`)">查看</a>
                <a @click="role(record.id)">角色</a>
                <a-popconfirm title="你确定删除么?" @confirm="deleteItem(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 群发通知 -->
    <backgNotice ref="ModalShow1" :selectedRowData="selectedRowData"></backgNotice>
    <!-- 分配角色 -->
    <backgAllocationRole ref="ModalShow2" :staffinformation="staffinformation" />
    <!-- 员工导入 -->
    <backgFileUpload ref="ModalShow3" :getSysUserData="getSysUserData"></backgFileUpload>
  </div>
</template>

<style lang="scss" scoped>
/* 使用深度选择器覆盖 ant-tree 的样式 */
:deep(.ant-tree .ant-tree-list-holder-inner) {
  justify-content: space-around;
  height: 550px;
}

.information {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  display: flex;

  &-member {
    margin: 0px 15px 10px 10px;
    display: flex;
    justify-content: space-between;
  }

}

.editable-row-operations a {
  margin-right: 8px;
}
</style>